package cn.gok.springsecuritydemo4.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
    基于url的权限配置
 */
//@Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().and()
                .authorizeRequests()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/getInfo").permitAll()
                .antMatchers("/user/**").hasRole("USER")
                //任何请求都需要认证
                .anyRequest().authenticated();

        http.csrf().disable();
    }

    //创建内存数据源，添加几个默认的用户
    @Override
    public UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager idm = new InMemoryUserDetailsManager();
        idm.createUser(
                User.withUsername("root")
                        .password("{noop}123")
                        .roles("ADMIN").build()
        );
        idm.createUser(
                User.withUsername("win7")
                        .password("{noop}123")
                        .roles("USER").build()
        );
        idm.createUser(
                User.withUsername("lisi")
                        .password("{noop}123")
                        .roles("READ_BOOK").build()
        );
        return idm;
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userDetailsService());
    }




}
